package test.concurrent;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

/**
 * 利用semaphore创建一个对象池
 *
 * @author yachao.guo
 * @date 2019-06-27 14:50
 */
public class ObjectPool<T, R> {


    final List<T> pool;
    final Semaphore semaphore;

    ObjectPool(int size, T t) {
        pool = new Vector<T>();
        for (int i = 0; i < size; i++) {
            pool.add(t);
        }
        semaphore = new Semaphore(size);
    }

    R exec(Function<T, R> fuc) {
        T t = null;
        try {
            semaphore.acquire();
            t = pool.remove(0);
            return fuc.apply(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            pool.add(t);
            semaphore.release();
        }

    }
    public static void main(String[] args) {
        ObjectPool<Integer, String> objectPool = new ObjectPool(4, 2);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                objectPool.exec(t -> {
                    System.out.println(t);
                    return t.toString();
                });
            }).start();

        }
    }
}
